package com.example.campusannouncement.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/lb-test")
public class LoadBalancerTestController {

    private static final Logger logger = LoggerFactory.getLogger(LoadBalancerTestController.class);
    
    @Value("${server.port}")
    private String serverPort;
    
    @Value("${spring.cloud.consul.discovery.instance-id:未知}")
    private String instanceId;
    
    @GetMapping
    public String loadBalancerTest(Model model) {
        logger.info("访问负载均衡测试页面");
        
        String hostName;
        String hostAddress;
        
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            hostName = localHost.getHostName();
            hostAddress = localHost.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取主机信息失败", e);
            hostName = "未知";
            hostAddress = "未知";
        }
        
        model.addAttribute("serverPort", serverPort);
        model.addAttribute("hostName", hostName);
        model.addAttribute("hostAddress", hostAddress);
        model.addAttribute("instanceId", instanceId);
        model.addAttribute("timestamp", System.currentTimeMillis());
        
        return "lb-test";
    }
    
    @GetMapping("/api")
    @ResponseBody
    @CrossOrigin(origins = {"http://localhost:8080", "http://localhost:8081"})
    public Map<String, Object> loadBalancerTestApi() {
        logger.info("访问负载均衡测试API");
        
        Map<String, Object> result = new HashMap<>();
        result.put("serverPort", serverPort);
        result.put("instanceId", instanceId);
        result.put("timestamp", System.currentTimeMillis());
        
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            result.put("hostName", localHost.getHostName());
            result.put("hostAddress", localHost.getHostAddress());
        } catch (UnknownHostException e) {
            logger.error("获取主机信息失败", e);
            result.put("hostName", "未知");
            result.put("hostAddress", "未知");
        }
        
        return result;
    }
} 